import random
import re

# Create your views here.
from django.shortcuts import redirect
from django.views import View
from django.http import JsonResponse
from django_redis import get_redis_connection
import logging

# 创建日志记录器
from rest_framework.decorators import action
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import CreateModelMixin, ListModelMixin, UpdateModelMixin
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet, GenericViewSet
from s1024.libs.qiniuyun.qiniu_storage import storage, QINIUYUN_URL
from s1024.utils.fastdfs.fastdfs_storage import FastDFSStorage
from users.models import User, Label
from users.serializers import ZhuceSerializer, UserViewSerializer

logger = logging.getLogger('django')
from users.libs.yuntongxun.sms import CCP


# 短信验证码
class SmsView(View):
    """短信验证码"""

    def get(self, request, mobile):
        if not re.match('\d{11}', mobile):
            return JsonResponse({
                'success': False,
                'message': '手机号格式错误'
            })
        # 创建连接到redis的对象
        redis_conn = get_redis_connection('verify_code')
        # 进入函数后, 先获取存储在 redis 中的数据
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        # 查看数据是否存在, 如果存在, 说明60s没过, 返回
        if send_flag:
            return JsonResponse({
                'success': False,
                'message': '发送短信过于频繁'})
        ccp = CCP()
        # 注意： 测试的短信模板编号为1
        sms_code = '%06d' % random.randint(0, 999999)
        a = ccp.send_template_sms(mobile, ['20200512', sms_code], 1)
        if a == -1:
            print('短信发送失败(测试)')
        # 存入redis数据库,为注册验证, 有效期300秒
        redis_conn.setex('sms_%s' % mobile, 300, sms_code)

        # 往 redis 中写入一个数据,为了下次获取验证码避免频繁
        # 我们给写入的数据设置为60s,如果过期,则会获取不到.
        redis_conn.setex('send_flag_%s' % mobile, 60, 1)
        # 打印日志(验证码)
        logger.info(sms_code)

        return JsonResponse({
            'success': True,
            'sms_code': sms_code,
            'message': '发送成功'
        })

# 注册
class RegisterView(CreateModelMixin, GenericAPIView):
    queryset = User.objects.all()
    # 设置序列化器属性
    serializer_class = ZhuceSerializer

    def post(self, request, *args, **kwargs):
        a = self.create(request, *args, **kwargs)
        return a

# 用户中心
class UserView(ListModelMixin, UpdateModelMixin, GenericViewSet):
    queryset = User.objects.all()
    serializer_class = UserViewSerializer
    # 显示个人信息
    def list(self, request, *args, **kwargs):
        user = request.user
        replies = user.replies.all()
        user.answer_question = []
        for i in replies:
            user.answer_question.append(i)
        serializer = self.get_serializer(user)
        return Response(serializer.data)
    # 修改个人信息
    def put(self, request):
        user = request.user
        serializer = self.serializer_class(instance=user,
                                           data=request.data,
                                           partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)
    # 修改密码
    @action(methods=['put'], detail=False)
    def password(self, request):
        dict = request.data
        user = request.user
        user.set_password(dict['password'])
        user.save()
        return Response({'success': True, 'message': '更新成功'})
    # 擅常的技术修改
    @action(methods=['put'], detail=False)
    def label(self, request):
        label = request.data['labels']
        user = request.user
        # 先移除所有的关注标签,在加入达成更新效果
        for x in user.labels.all():
            request.user.labels.remove(x)
        for i in label:
            a = Label.objects.get(id=i)
            user.labels.add(a)
        return Response({"success": True, "message": "修改成功"})





#关注和取消关注
class LikeView(APIView):
    def post(self,request ,pk):
        user = User.objects.get(id=pk)
        if user == request.user:
            return Response({"message": "自己不能关注自己哦"})
        user.fans.add(request.user)
        return JsonResponse({
            'message':'关注成功',
            'success': 'True'
        })
    def delete(self, request, pk):
        user = User.objects.get(id=pk)
        user.fans.remove(request.user)
        return JsonResponse({
            'message': '取消关注成功',
            'success': 'True'
        })


# 前端富文本图片
class CommonView(APIView):
    def post(self, request):
        # 接收参数
        img = request.data.get("upload")

        ret = FastDFSStorage.save(self, name='name.jpg', content=img, max_length=None)
        url = FastDFSStorage.url(self, ret)
        # 拼接前段需要的图片链接，不然显示不了
        img_url = "http://127.0.0.1:8080/upload_success.html?image_url=" + url + "&CKEditorFuncNum=1"
        # 返回重定向
        return redirect(img_url)


# 上传头像
class UserAvatarView(APIView):
    def post(self, request):
        img = request.FILES.get('img', None)
        if img:
            img_url = storage(img.read())
            avatar_url = QINIUYUN_URL + img_url
            # 不用保存,这只是获取图片链接的接口 保存功能在修改个人中心实现
            # request.user.avatar = avatar_url
            # request.user.save()
            return Response({'imgurl':avatar_url})
        else:
            return Response({
                "errno": "4002	",
                "errmsg": "无数据"
            })